<template>
  <div>
    <searchBox @handleSearch="handleQuery" @handleReset="handleReset">
      <el-form :model="queryParams.param" ref="ArticlesForm" :inline="true">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model.trim="queryParams.param.title" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="关键字" prop="content">
          <el-input v-model.trim="queryParams.param.content" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="来源语言" prop="languageId">
          <el-select style="width: 200px" v-model="queryParams.param.languageId" placeholder="请选择" clearable>
            <el-option v-for="dict in sys_language_type" :key="dict.id" :label="dict.description" :value="dict.id"
              :disabled="!dict.status"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布站点" prop="websiteId">
          <el-select style="width: 200px" v-model="queryParams.param.websiteId" placeholder="请选择" clearable>
            <el-option v-for="dict in host_type" :key="dict.id" :label="dict.name" :value="dict.id"
              :disabled="!dict.status"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </searchBox>
    <el-table :data="articlesList" style="height: calc(100vh - 250px)" @row-click="handleRowClick">
      <el-table-column>
        <template #header>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </template>
        <template #default="scope">
          <div style="display: flex;align-items: center;gap: 50px;">
            <div style="width: 200px;">
              <image-preview :src="scope.row.host" fit="scale-down" :width="200" :height="200" />
            </div>

            <div>
              <h2>{{ scope.row.title }}</h2>
              <el-button>{{ scope.row.labelContent }}</el-button>
              <el-button>{{ scope.row.countryName }}</el-button>
              <el-button>{{ scope.row.languageName }}</el-button>
              <el-button>{{ scope.row.siteArticleCategoryName }}</el-button>

              <div style="margin: 10px 0; width: calc(100% - 400px)" id="output">
                <el-text line-clamp="3" v-html="scope.row.newContent"></el-text>
              </div>

              <el-text> 共发布{{ scope.row.siteLength }}个站点</el-text>
              <el-button class="mb8" style="margin-left: 10px" type="primary" v-if="scope.row.siteLength"
                @click.stop="viewSiteList(scope.row)">查看更多</el-button>
              <el-button class="mb8" style="margin-left: 10px" link :icon="User">作者：{{ scope.row.author }}</el-button>
              <el-button class="mb8" style="margin-left: 10px" link :icon="Clock">{{
                scope.row.newCreated
                }}</el-button>
              <el-button class="mb8" style="margin-left: 10px" link :icon="View">{{
                scope.row.visits
                }}</el-button>
              <el-button class="mb8" style="margin-left: 10px" type="primary"
                @click.stop="releaseSite(scope.row)">发布</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :limit="queryParams.pageSize" :page="queryParams.pageNum" @pagination="handlePageChange">
    </Pagination>
    <publicSite :dialogVisible="viewDetailVisible" @handleListClose="handleListClose" :listItem="publicItem">
    </publicSite>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from "vue";
import publicSite from "@/views/publicSite";
import { useRouter, useRoute } from "vue-router";

import { Clock, User, View } from "@element-plus/icons-vue";
const router = useRouter();
const host_type = ref([]); //来源网站
const { proxy } = getCurrentInstance();
const sys_language_type = ref([]); //获取语言类别
const articlesList = ref([]);
const total = ref(0);
const viewDetailVisible = ref(false);
const publicItem = ref({}); //公共赋值对象数据

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  param: {},
});
onMounted(() => {
  getLanguage();
  getList();
});
const getList = () => {
  site.general
    .sitearticleList({
      data: queryParams.value,
    })
    .then((res) => {
      total.value = res.total;
      if (res.data?.length) {
        res.data = res.data.map((code) => {
          return {
            ...code,
            siteLength: code.websiteIds?.length || 0,
            newContent: processingImage(code),
            newCreated:  proxy.DateTime(code.created),
          };
        });
      }
      articlesList.value = res.data;
    });
};
const releaseSite = (row) => {
  proxy.$modal.confirm("是否确认发布此文章？").then(() => {
    site.general
      .sitearticlePublish({
        data: {
          ids: [row.id],
        },
      })
      .then((res) => {
        if (res.code === 200) {
          getList();
          proxy.$message.success("发布成功");
        }
      });
  });
};
// 搜索
const handleQuery = () => {
  getList();
};
// 搜索
const handleReset = () => {
  proxy.resetForm("ArticlesForm");
  getList();
};
// 查看更多站点取消事件
const handleListClose = () => {
  viewDetailVisible.value = false;
};
const handleAdd = () => {
  router.push({ path: `components/articlesIntegration`, query: {} });
};
const handleRowClick = (row, column, event) => {
  router.push({ path: `components/articlesIntegration`, query: {id:row.id} });
};
const processingImage = (code) => {
  let newContent = decodeURIComponent(code.content);
  const isPreTag = /^<pre[\s>]/.test(newContent); // 检查是否是pre标签
  if (isPreTag) {
    newContent = newContent
      .replace(/<pre[^>]*>|<\/pre>/g, '') // 移除 <pre> 标签
      .replace(/&lt;/g, '<') // 解码 <
      .replace(/&gt;/g, '>'); // 解码 >
  } else {
    newContent = newContent.replace(/<img([^>]*)>/gi, (match) => {
      return match.replace(/\/?>/i, ' class="image-custom-size" />');
    });
  }
  return newContent;
};

const getLanguage = () => {
  // 获取语言
  product.language.languageList().then((res) => {
    sys_language_type.value = res.data;
  });

  // 所属站点
  site.general
    .sitewebsiteList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {},
      },
    })
    .then((res) => {
      host_type.value = res.data;
    });
};
// 分页
const handlePageChange = (newPage) => {
  queryParams.value.pageNum = newPage.page;
  queryParams.value.pageSize = newPage.limit;
  getList();
};
// 查看更多站点
const viewSiteList = (rowItem) => {
  publicItem.value = rowItem;
  viewDetailVisible.value = true;
};
</script>
<style>
.image-custom-size {
  width: 150px;
  height: 150px;
}
</style>